﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;

namespace ntools.NetduinoGo.PlusModule.NetduinoPlus
{
    public class Program
    {
        private static Thread IpChecker = new Thread(IPChecker);
        private static AutoResetEvent reset = new AutoResetEvent(false);
        public static string IP = "0.0.0.0";

        public static bool ComLinkUp = false, NetworkAvailable = false, StopIPChecker = false;
        public static bool FirstPing = true;

        private static Link link;

        public static void Main()
        {
            Program.IpChecker.Start();
            if (!reset.WaitOne(1000, false))
                StopIPChecker = true;
            else
                Program.NetworkAvailable = true;

            Microsoft.SPOT.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged += new Microsoft.SPOT.Net.NetworkInformation.NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
            Microsoft.SPOT.Net.NetworkInformation.NetworkChange.NetworkAddressChanged += new Microsoft.SPOT.Net.NetworkInformation.NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);

            link = new Link();

            Thread.Sleep(-1);
        }

        public static void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
        {
            Program.IP = Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress;
        }

        public static void NetworkChange_NetworkAvailabilityChanged(object sender, Microsoft.SPOT.Net.NetworkInformation.NetworkAvailabilityEventArgs e)
        {
            Program.NetworkAvailable = e.IsAvailable;
        }

        public static void IPChecker()
        {
            while (Program.IP == "0.0.0.0" && !Program.StopIPChecker)
            {
                Program.IP = Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress;
            }

            reset.Set();
        }
    }
}
